//
//  ST_MaidWayWebViewController.swift
//  maid
//
//  Created by DC on 2022/3/15.
//

import UIKit
import WebKit

class ST_MaidWayWebViewController: UIViewController {

    var webView: WKWebView?
    
    var urlStr: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .clear
        
        initial_web_view()
        
        self.view.addSubview(animationView)
        animationView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: 400, height: 400))
        }
        
        if let url = URL(string: urlStr) {
            animationView.play()
            webView!.load(URLRequest(url: url))
        }else {
            back()
        }
    }
    
    fileprivate func initial_web_view() {
        webView = WKWebView()
        guard let stronglyWeb = webView else {
            self.back()
            return
        }
        stronglyWeb.backgroundColor = .clear
        stronglyWeb.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 0.1)
        stronglyWeb.navigationDelegate = self
        self.view.addSubview(stronglyWeb)
    }
    
    fileprivate func back() {
        self.goback_previous_controller(animated: false)
    }
    
    fileprivate lazy var animationView: LOTAnimationView = {
        let path = Bundle.main.path(forResource: "way", ofType: "json")
        let l = LOTAnimationView(filePath: path!)
        l.contentMode = .scaleAspectFill
        l.loopAnimation = true
        return l
    }()
}

extension ST_MaidWayWebViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        animationView.stop()
        self.toast(text: "请稍后再试")
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            self.back()
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let request = navigationAction.request
        guard let url = request.url else {
            decisionHandler(.allow)
            return
        }
        
        let scheme = url.scheme
        if scheme != "https" && scheme != "http" {
            if scheme == "weixin" {
                animationView.stop()
                if UIApplication.shared.canOpenURL(url) {
                    self.dismiss(animated: false) {
                        UIApplication.shared.open(url, options: [:], completionHandler: nil)
                    }
                }else {
                    self.toast(text: "无法打开微信，请确定微信是否安装")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        self.back()
                    }
                }
            }
            if scheme == "alipay" {
                let aString = url.absoluteString.urlDecoded
                var urls = aString.split(separator: "?").map({
                    String($0)
                })
                
                if urls.count < 1 {
                    self.toast(text: "网络开小差了，请稍后再试")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        self.back()
                    }
                    return
                }
                
                let jsonData = urls[1].data(using: .utf8)
                let json = try? JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers) as? [String: Any]
                guard var dict = json else {
                    self.toast(text: "网络开小差了，请稍后再试")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        self.back()
                    }
                    return
                }
                
                dict["fromAppUrlScheme"] = "www.jingniaoapps.com"
                guard let stringData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) else {
                    self.toast(text: "网络开小差了，请稍后再试")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        self.back()
                    }
                    return
                }
                
                urls[1] = String.init(data: stringData, encoding: .utf8)!.urlEncoded
                let openUrl = urls.joined(separator: "?")
                guard let goAUrl = URL(string: openUrl) else {
                    self.toast(text: "网络开小差了，请稍后再试")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        self.back()
                    }
                    return
                }
                
                animationView.stop()
                if UIApplication.shared.canOpenURL(goAUrl) {
                    self.dismiss(animated: false) {
                        UIApplication.shared.open(goAUrl, options: [:], completionHandler: nil)
                    }
                }else {
                    self.toast(text: "无法打开支付宝，请确定支付宝是否安装")
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        self.back()
                    }
                }
            }
        }
        
        decisionHandler(.allow)
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        var request: URLRequest?
        let urlString = webView.url?.absoluteString ?? ""
        
        if urlString.hasPrefix("https://wx.tenpay.com") && !urlString.contains("redirect_url=www.jingniaoapps.com://") {
            let wScheme = "www.jingniaoapps.com"
            let referer = String(format: "%@://", wScheme)
            
            let range = urlString.range(of: "redirect_url=")
            var reqUrl: String?
            if range != nil {
                let re = urlString[urlString.startIndex ..< range!.lowerBound]
                reqUrl = re.appending(String(format: "&redirect_url=%@", referer))
            }else {
                reqUrl = urlString.appending(String(format: "&redirect_url=%@", referer))
            }
            request = URLRequest(url: URL(string: reqUrl!)!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
            request?.setValue("http://www.jingniaoapps.com/", forHTTPHeaderField: "Referer")
            if self.webView != nil {
                self.webView?.removeFromSuperview()
                self.webView = nil
            }
            self.webView = WKWebView()
            guard let stronglyWeb = self.webView, let stronglyRequest = request else {
                self.toast(text: "网络开小差了，请稍后再试")
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    self.back()
                }
                return
            }
            stronglyWeb.backgroundColor = .clear
            stronglyWeb.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 0.1)
            stronglyWeb.navigationDelegate = self
            self.view.addSubview(stronglyWeb)
            stronglyWeb.load(stronglyRequest)
        }
    }
    
}
